package com.zgzg.shop.pay.base.utils;

import cn.hutool.core.date.DatePattern;
import com.google.gson.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <em color="#DC143C">
 *     <b>gson工具类 仅供测试打印</b>
 * </em>
 *
 * @author zzl
 * @date 2021-07-14
 */
public final class GsonUtil {

    private GsonUtil() {
    }

    private static final Gson GSON  = new GsonBuilder()
            .disableHtmlEscaping()
            .setPrettyPrinting()
            .registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (localDateTime, type, jsonSerializationContext)
                    -> new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)))).create();

    /**
     * Gson对象转换为字符串并格式化
     *
     * @param object 待转换的对象
     * @return string 返回格式化后的json字符串
     */
    public static String getPrettyGsonStr(Object object) {
        return GSON.toJson(object);
    }

    /**
     * 输出格式化的json字符串
     *
     * @param object 待输出的对象
     */
    public static void printPrettyGsonStr(Object object) {
        System.out.println(getPrettyGsonStr(object));
    }
}
